import { writeToFile } from "./xlsx.js";
import { groupBy } from "lodash-es";
import dayjs from "dayjs";
import { sum, tryFilePath } from "./util.js";
import path from "path";

function getPosAmount(type, amount) {
  const posAmount = ["", "", ""];
  switch (type) {
    case "中央预算内投资":
    case "超长期特别国债":
      posAmount[0] = amount;
      break;
    case "省预算内前期工作经费":
    case "省预算内基本建设投资":
      posAmount[1] = amount;
      break;
    default:
      posAmount[2] = amount;
      break;
  }
  return posAmount;
}

export function saveAs(filtered) {
  const d = [];
  filtered.forEach((item) => {
    item.funds.forEach((fund) => {
      d.push({
        ...item,
        fund,
      });
    });
  });

  d.sort((a, b) => {
    if (dayjs(a.fund.doc.date).isValid() && dayjs(b.fund.doc.date).isValid()) {
      return dayjs(a.fund.doc.date).isBefore(dayjs(b.fund.doc.date)) ? -1 : 1;
    } else {
      return 1;
    }
  });

  const fundNames = d.map((item) => item.fund.name);
  const groupSort = Array.from(new Set(fundNames));

  const total = sum(d.map((item) => item.fund.amount));
  const totalCentral = sum(
    d.map((item) =>
      item.fund.type === "中央预算内投资" || item.fund.type === "超长期特别国债" ? item.fund.amount : 0
    )
  );
  const totalProvince = sum(
    d.map((item) =>
      item.fund.type === "省预算内前期工作经费" ||
      item.fund.type === "省预算内基本建设投资"
        ? item.fund.amount
        : 0
    )
  );

  const group = groupBy(d, "fund.name");

  const sumaryStr = `合计（${Object.keys(group).length} 个专项）`;
  const rows = [
    [
      "",
      sumaryStr,
      "-",
      d.length,
      sum(d.map((item) => item.investment)),
      "-",
      "-",
      "-",
      "-",
      "-",
      total,
      totalCentral,
      totalProvince,
      "",
      "-",
    ],
  ];

  for (const name of groupSort) {
    const items = group[name];
    const type = items[0].fund.type;
    const posAmount = getPosAmount(
      type,
      sum(items.map((item) => item.fund.amount))
    );
    rows.push([
      "",
      name,
      "",
      items.length,
      "",
      dayjs(items[0].fund.doc.date).format("YYYY年M月"),
      items[0].fund.doc.code,
      items[0].fund.forward_doc.code,
      "",
      items[0].fund.type,
      sum(items.map((item) => item.fund.amount)),
      ...posAmount,
      "",
    ]);
    items.forEach((item, i) => {
      const posAmount = getPosAmount(type, item.fund.amount);

      rows.push([
        i + 1,
        item.name,
        item.area,
        "",
        item.investment,
        "",
        "",
        "",
        "",
        "",
        item.fund.amount,
        ...posAmount,
        item.department,
      ]);
    });
  }
  const tpl = path.join("template", "department_template.xlsx");
  const target = path.join("dist", "争取资金分科室.xlsx");
  writeToFile(tpl, tryFilePath(target), rows);
}
